import {
  setStorageToken,
  isGivenTokenEmpty,
  getStorageToken,
} from "./tokenService";
import axiosApiInstance from "../api/axiosAPIClient";
import { getAPIPrefix } from "./wrapperService";

const BASE_AUTH_API_URL = process.env.REACT_APP_AUTHAPI_URL;
export const refreshToken = async (token) => {
  try {
  
    if (isGivenTokenEmpty(token)) {
      token = getStorageToken();
    }
    const response = await axiosApiInstance.post(
      `${BASE_AUTH_API_URL}${getAPIPrefix()}/Account/RenewToken?jwtToken=${token}`
    );

    if (response.status === 200) {
      const json = await response.data;
      setStorageToken(json);
      return json;
    } else {
      setStorageToken("");
      return "";
    }
  } catch (err) {
    console.log("err " + err);
    throw new Error("Invalid User");
  }
};

export const UserPrivileges = async (userID) => {
  try {
    const privilegesRes = await axiosApiInstance.post(
      `${BASE_AUTH_API_URL}api/${getAPIPrefix()}/UserManagement/GetApplicationPrivileges/`,
      { securityAppName: "RAP", userID: userID }
    );
    if (privilegesRes.status === 200) {
      return await privilegesRes.data;
    }
  } catch (err) {
    console.log("err " + err);
    throw new Error("Invalid User");
  }
};

export const UserProfile = async (emailID) => {
  try {
    const response = await axiosApiInstance.get(
      `${BASE_AUTH_API_URL}api/${getAPIPrefix()}/account/GetUserDetails?emailid=${emailID}`
    );

    if (response.status === 200) {
      const userinfo = await response.data;
      return userinfo;
    }
  } catch (err) {
    console.log("err " + err);
    throw new Error("Invalid User");
  }
};
